# file: /data/pyworks/fw_paddleocr_web/app/modules/table_cell_detection.py
from typing import Dict, Any, List
import cv2
import numpy as np
from app.utils.logger import get_logger

logger = get_logger(__name__)


# 表格单元格检测模块
class TableCellDetectionModule:
    _instance = None
    _initialized = False

    def __new__(cls):
        if cls._instance is None:
            cls._instance = super(TableCellDetectionModule, cls).__new__(cls)
        return cls._instance

    def __init__(self):
        if not self._initialized:
            logger.info("Initializing TableCellDetectionModule")
            self._initialized = True

    def detect(self, image_data: bytes, table_bbox: List[int]) -> Dict[str, Any]:
        """
        检测表格单元格

        Args:
            image_data: 图像字节数据
            table_bbox: 表格边界框 [x1, y1, x2, y2]

        Returns:
            表格单元格检测结果
        """
        try:
            # 将字节数据转换为OpenCV图像
            nparr = np.frombuffer(image_data, np.uint8)
            img = cv2.imdecode(nparr, cv2.IMREAD_COLOR)

            # 在表格区域内检测单元格
            cells = self._detect_cells_in_table(img, table_bbox)

            # 对每个单元格进行文本识别（模拟）
            for cell in cells:
                cell_text = self._recognize_cell_text(img, cell["bbox"])
                cell["text"] = cell_text

            return {
                "table_bbox": table_bbox,
                "cells": cells,
                "cell_count": len(cells)
            }

        except Exception as e:
            raise RuntimeError(f"Table cell detection failed: {str(e)}")

    def _detect_cells_in_table(self, img, table_bbox: List[int]) -> List[Dict]:
        """在表格区域内检测单元格"""
        x1, y1, x2, y2 = table_bbox
        table_width = x2 - x1
        table_height = y2 - y1

        # 模拟单元格检测结果 (3行4列)
        cells = []
        row_height = table_height // 3
        col_width = table_width // 4

        for row in range(3):
            for col in range(4):
                cell_x1 = x1 + col * col_width
                cell_y1 = y1 + row * row_height
                cell_x2 = cell_x1 + col_width
                cell_y2 = cell_y1 + row_height

                cells.append({
                    "bbox": [cell_x1, cell_y1, cell_x2, cell_y2],
                    "row": row,
                    "col": col,
                    "confidence": 0.90
                })

        return cells

    def _recognize_cell_text(self, img, bbox: List[int]) -> str:
        """识别单元格文本"""
        # 模拟文本识别结果
        return f"Cell {bbox[0] // 10}_{bbox[1] // 10}"
